package com.bkhech.home.practice.javacore.string_to_hash;

/**
 * 字符串 转 hash码
 *
 * @author guowm
 * @date 2022/8/24
 */
public class StringToHash {
    public static void main(String[] args) {
        String strs = "zh";
        int hashCode = toHash(strs);
        System.out.println(hashCode);
    }

    private static int toHash(String strs) {
        //数组大小一般取质数
        int arraySize = 1111111113;
        int hashCode = 0;
        for (int i = 0; i < strs.length(); i++) {
            //将获取到的字符串转换成数字，比如a的码值是97，则97-96=1 就代表a的值
            int letterValue = strs.charAt(i) - 96;
            //防止编码溢出，对每步结果都进行取模运算
            hashCode = ((hashCode << 5) + letterValue) % arraySize;
        }
        return hashCode;
    }
}
